package com.example.appusagestats.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.appusagestats.R
import com.example.appusagestats.model.AppUsageInfo

class AppUsageAdapter(
    private var appUsageList: List<AppUsageInfo>,
    private val onItemClick: (AppUsageInfo) -> Unit
) : RecyclerView.Adapter<AppUsageAdapter.ViewHolder>() {

    class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val appIcon: ImageView = view.findViewById(R.id.appIcon)
        val appName: TextView = view.findViewById(R.id.appName)
        val packageName: TextView = view.findViewById(R.id.packageName)
        val usageTime: TextView = view.findViewById(R.id.usageTime)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.item_app_usage, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val appUsage = appUsageList[position]
        
        holder.appName.text = appUsage.appName
        holder.packageName.text = appUsage.packageName
        holder.usageTime.text = appUsage.getFormattedUsageTime()
        
        appUsage.appIcon?.let { icon ->
            holder.appIcon.setImageDrawable(icon)
        } ?: run {
            holder.appIcon.setImageResource(R.drawable.ic_default_app)
        }

        holder.itemView.setOnClickListener {
            onItemClick(appUsage)
        }
    }

    override fun getItemCount() = appUsageList.size

    fun updateData(newList: List<AppUsageInfo>) {
        appUsageList = newList
        notifyDataSetChanged()
    }

    fun sortByTime() {
        val sortedList = appUsageList.sortedByDescending { it.totalTimeInForeground }
        updateData(sortedList)
    }

    fun sortByName() {
        val sortedList = appUsageList.sortedBy { it.appName }
        updateData(sortedList)
    }
} 